/**
 * Copyright (c) 2008-2010 The Open Source Geospatial Foundation
 * 
 * Published under the BSD license.
 * See http://svn.geoext.org/core/trunk/geoext/license.txt for the full text
 * of the license.
 */

/** api: example[toolbar]
 *  Toolbar with Actions
 *  --------------------
 *  Create a toolbar with GeoExt Actions.
 */

Ext.onReady(function() {
    Ext.QuickTips.init();

    map = new OpenLayers.Map();
	map.addControl(new OpenLayers.Control.LayerSwitcher());
    
    var gphy = new OpenLayers.Layer.Google(
        "Google Physical",
        {type: google.maps.MapTypeId.TERRAIN}
    );
    var gmap = new OpenLayers.Layer.Google(
        "Google Streets", // the default
        {numZoomLevels: 20}
    );
    var ghyb = new OpenLayers.Layer.Google(
        "Google Hybrid",
        {type: google.maps.MapTypeId.HYBRID, numZoomLevels: 20}
    );
    var gsat = new OpenLayers.Layer.Google(
        "Google Satellite",
        {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22}
    );

    map.addLayers([ghyb, gphy, gmap, gsat]);


		var osm = new OpenLayers.Layer.OSM();

        map.addLayers([osm, gphy, gmap, ghyb, gsat]);

        



//    var wms = new OpenLayers.Layer.WMS(
//        "Global Imagery",
//        "http://maps.opengeo.org/geowebcache/service/wms",
//        {layers: "bluemarble"}
//    );
     vector = new OpenLayers.Layer.Vector("vector");
    map.addLayers([vector]);
    
    var ctrl, toolbarItems = [], action, actions = {};

//    // ZoomToMaxExtent control, a "button" control
//    action = new GeoExt.Action({
//        control: new OpenLayers.Control.ZoomToMaxExtent(),
//        map: map,
//        text: "max extent",
//        tooltip: "zoom to max extent"
//    });
//    actions["max_extent"] = action;
//    toolbarItems.push(action);
//    toolbarItems.push("-");

    // Navigation control and DrawFeature controls
    // in the same toggle group
    action = new GeoExt.Action({
        text: "Pan",
        control: new OpenLayers.Control.Navigation(),
        map: map,
        // button options
        toggleGroup: "draw",
        allowDepress: false,
        pressed: true,
        tooltip: "navigate",
        // check item options
        group: "draw",
        checked: true
    });
    actions["nav"] = action;
    toolbarItems.push(action);

    action = new GeoExt.Action({
        text: "Draw Impact Area",
        control: new OpenLayers.Control.DrawFeature(
            vector, OpenLayers.Handler.Polygon
        ),
        map: map,
        // button options
        toggleGroup: "draw",
        allowDepress: false,
        tooltip: "draw polygon",
        // check item options
        group: "draw"
    });
    actions["drawpolygon"] = action;
    toolbarItems.push(action);

    action = new GeoExt.Action({
        text: "Edit",
        control: new OpenLayers.Control.ModifyFeature(
            vector
        ),
        map: map,
        // button options
        toggleGroup: "draw",
        allowDepress: false,
        tooltip: "Edit",
        // check item options
        group: "draw"
    });
    actions["edit"] = action;
	toolbarItems.push(action);
//	action = new GeoExt.Action({
//        text: "Draw Marker",
//        control: new OpenLayers.Control.DrawFeature(
//            vector, OpenLayers.Handler.Point
//        ),
//        map: map,
//        // button options
//        toggleGroup: "draw",
//        allowDepress: false,
//        tooltip: "Set Marker",
//        // check item options
//        group: "draw"
//    });
//    actions["drawmarker"] = action;
	
    //toolbarItems.push(action);
   // toolbarItems.push("-");

    // SelectFeature control, a "toggle" control
    action = new GeoExt.Action({
        text: "Select",
        control: new OpenLayers.Control.SelectFeature(vector, {
            type: OpenLayers.Control.TYPE_TOGGLE,
            hover: false
        }),
        map: map,
        // button options
        //enableToggle: true,
		gruop: 'draw',
		toggleGroup: "draw",
        tooltip: "select feature"
    });
    actions["select"] = action;
    toolbarItems.push(action);
		action = new GeoExt.Action({
		text: 'Set Marker',
		handler: function(){
			var i,fe;
			var fes = vector.features;
			var impacts = [];
			for (i=0;i<fes.length;i++){
				
				fe = fes[i];
				
				if (fe.geometry.CLASS_NAME=="OpenLayers.Geometry.Polygon"){
					//it is an impact
					var pt = new OpenLayers.Feature.Vector(fe.geometry.getCentroid());
					pt.attributes['parent'] = fe.id;
					
					impacts.push(pt)
					//pt.attributes['parent'] = fe.id;
				}
			}
			vector.addFeatures(impacts); 
            
			
        }

	})
	toolbarItems.push(action);
	action = new GeoExt.Action({
		text: 'Delete',
		handler: function(){
			var i, fe;
			var fes = vector.selectedFeatures;
			var impacts = [];
			for (i=0;i<fes.length;i++){
				fe = fes[i];
				fe.destroy();				
			}
            
			
        }

	})
	toolbarItems.push(action);
    toolbarItems.push("-");

    // Navigation history - two "button" controls
    ctrl = new OpenLayers.Control.NavigationHistory();
    map.addControl(ctrl);

    action = new GeoExt.Action({
        text: "previous",
        control: ctrl.previous,
        disabled: true,
        tooltip: "previous in history"
    });
    actions["previous"] = action;
    toolbarItems.push(action);

    action = new GeoExt.Action({
        text: "next",
        control: ctrl.next,
        disabled: true,
        tooltip: "next in history"
    });
    actions["next"] = action;
    toolbarItems.push(action);
	
    toolbarItems.push("->");

    // Reuse the GeoExt.Action objects created above
    // as menu items
//    toolbarItems.push({
//        text: "menu",
//        menu: new Ext.menu.Menu({
//            items: [
//                // ZoomToMaxExtent
//                actions["max_extent"],
//                // Nav
//                new Ext.menu.CheckItem(actions["nav"]),
//                // Draw poly
//                new Ext.menu.CheckItem(actions["draw_poly"]),
//                // Draw line
//                new Ext.menu.CheckItem(actions["draw_line"]),
//                // Select control
//                new Ext.menu.CheckItem(actions["select"]),
//                // Navigation history control
//                actions["previous"],
//                actions["next"]
//            ]
//        })
//    });

	
	action = new GeoExt.Action({
		text: 'Submit Form',
		handler: function(){
			var i, fe;
			var fes = vector.features;
			var impacts = [];
			var results = '';
			for (i=0;i<fes.length;i++){
				fe = fes[i];
				if (fe.geometry.CLASS_NAME=="OpenLayers.Geometry.Polygon"){
					//it is an impact
					results = results + '\n' + 'polygon: ' + fe.id + '\n' + fe.geometry.toString();
					
				} else if (fe.geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){
					//it is an marker
					results = results + '\n' + 'The center of : ' + fe.attributes.parent + '\n' + fe.geometry.toString();
				}
				
			}
			
			alert(results)
            
			
        }

	})
	toolbarItems.push(action);



    var mapPanel = new GeoExt.MapPanel({
//        renderTo: "mappanel",
        height: 400,
        width: 600,
        map: map,
        center: new OpenLayers.LonLat(-83.019919, 40.001405).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()),
        zoom: 15,
        tbar: toolbarItems
    });

editform = new Ext.FormPanel({
        labelAlign: 'top',
        frame:true,
        title: 'Construction Impact Form',
        bodyStyle:'padding:5px 5px 0',
        width: 600,
		autoScroll: true,
		reader: new Ext.data.JsonReader({
			root: 'record',
			fields: ['project', {
				name: 'start',
				type: 'date',
				dateFormat: 'm/d/Y'
			}, {
				name: 'end',
				type: 'date',
				dateFormat: 'm/d/Y'
			}, 'projectid', 'pm']
		}),
        items: [{
                    xtype:'textfield',
                    fieldLabel: 'ID',
                    name: 'projectid',
                    anchor:'95%',
					width: 10
                },{
            layout:'column',
            items:[{
                columnWidth:.2,
                layout: 'form',
                items: [{
                    xtype:'textfield',
                    fieldLabel: 'Project',
                    name: 'project',
                    anchor:'95%'
                }, {
                    xtype:'datefield',
                    fieldLabel: 'Start',
                    name: 'start',
                    anchor:'95%'
                },{
                    xtype:'textfield',
                    fieldLabel: 'PM',
                    name: 'pm',
                    anchor:'95%'
                }]
            },{
                columnWidth:.2,
                layout: 'form',
                items: [
				{
                    xtype:'textfield',
                    fieldLabel: 'Project#',
                    name: 'projectno',
                    anchor:'95%'
                },{
                    xtype:'datefield',
                    fieldLabel: 'End',
                    name: 'end',
                    anchor:'95%'
                }]
            },{
                columnWidth:.2,
                layout: 'form',
                items: [{
			xtype:'fieldset',
			autoHeight:true,
			autoWidth: true,
			width: 200,
			title: 'Impacts',
			defaultType: 'checkbox',
			items: [
                {boxLabel: 'Sidewalk', name: 'sidewalk', hideLabel: true},
                {boxLabel: 'Roadway', name: 'roadway',hideLabel: true},
                {boxLabel: 'Garage', name: 'garage',hideLabel: true},
                {boxLabel: 'ADA Parking', name: 'adaparking', hideLabel: true}
            ]
        }]
            }]
        },{xtype:'fieldset',
			autoHeight:true,
			width: 600,
			title: 'Description',
			collapsible: true,
			items: [{
            xtype:'htmleditor',
			name: 'description',
            id:'bio',
//            fieldLabel:'Description',
			height:200,
			hideLabel: true,
            anchor:'98%'
        }]
			},
		 mapPanel],

        buttons: [{
            text: 'Save',
			handler: function(){
				var osurecord = Ext.data.Record.create(['project', {
				name: 'start',
				type: 'date',
				dateFormat: 'm/d/Y'
			}, {
				name: 'end',
				type: 'date',
				dateFormat: 'm/d/Y'
			}, 'projectid', 'pm', {name:'sidewalk', type: 'bool'}, 'garage']);
			var osudata = new osurecord({project: 'Project', 
			start: '02/05/2010', end: '04/09/2015', projectid: 'OSU-123', end: '5/9/2010',
			description: '<h1>i am trying to see if it is working</h2>', garage: true, sidewalk: true});
//				editform.getForm().load({url:'osudata.js', waitMsg:'Loading'})
				editform.getForm().loadRecord(osudata)
			}
        },{
            text: 'Cancel'
        }]
    });//end of editform
	
    //north, the header
    var header = new Ext.Panel({
        border: false,
        layout: 'anchor',
        region: 'north',
        cls: 'docs-header',
        height: 30,
        items: [{
            xtype: 'box',
            el: 'header',
            border: false,
            anchor: 'none 0'
        }]
    });//end of header
	


//   Define the Grid data and create the Grid
    var myData = [
        [1, 'project', '02/05/1978', '02/09/2045', 'OSU-12345', 'Mel meng', true, true, true, true, '<h1>header1</h1>'],
		[2, 'project2', '02/05/1918', '01/09/2045', 'OSU-12345, 2', 'Mel meng ', true, false, false, true,'<h1>header1 2</h1>']
    ];

    var ds = new Ext.data.Store({
        reader: new Ext.data.ArrayReader({}, ['projectid', 'project', {
				name: 'start',
				type: 'date',
				dateFormat: 'm/d/Y'
			}, {
				name: 'end',
				type: 'date',
				dateFormat: 'm/d/Y'
			}, 'projectno', 'pm', 'sidewalk','roadway','garage','adaparking',  'description'])
    });
	
    // the DefaultColumnModel expects this blob to define columns. It can be extended to provide
    // custom or reusable ColumnModels
    var cm = new Ext.grid.ColumnModel([
        {id:'projectid',header: "ID", width: 160, sortable: true, locked:false, dataIndex: 'projectid'},
        {header: "Start", width: 55, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'start'},
		{header: "End", width: 55, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'end'},
        {header: "Project", width: 55, sortable: true, dataIndex: 'project'},
		{header: "Project#", width: 55, sortable: true, dataIndex: 'projectno'},
		{header: "PM", width: 55, sortable: true, dataIndex: 'pm'},
        {header: "sidewalk", width: 65, sortable: true, dataIndex: 'sidewalk'},
		{header: "roadway", width: 65, sortable: true, dataIndex: 'roadway'},
		{header: "garage", width: 65, sortable: true, dataIndex: 'garage'},
		{header: "adaparking", width: 65, sortable: true, dataIndex: 'adaparking'},
		{header: "description", width: 65, sortable: true, dataIndex: 'description', hidden: true }
		
    ]);



	
var gridPanel = new Ext.grid.GridPanel({
	store: ds,
	cm: cm,
	sm: new Ext.grid.RowSelectionModel({
		singleSelect: true,
		listeners: {
			rowselect: function(sm, row, rec){
				editform.getForm().loadRecord(rec)
			}
		}
	}),
	height: 500,
	title: 'Impact List',
	border: true,
	listeners: {
		viewready: function(g){
			
			g.getSelectionModel().selectRow(0);
		}
	}
});//end of gridpanel


ds.loadData(myData);




var viewport = new Ext.Viewport({
                layout: 'border',
                items: [header, {
                    region: 'south',
                    border: true,
                    html: '<div style="text-align: center;font-size: 80%;color:black;">OSU Constructin Impact Editor - by Mel Meng May 2009, <a href="http://www.dlz.com">DLZ</a>. ymeng@dlz.com<div>'
                
                }, {
                    region: 'west',
                    layout: 'fit',
                    split: true,
                    width: 300,
                    minSize: 175,
                    maxSize: 400,
                    collapseMode: 'mini',
                    collapsible: true,
                    autoScroll: false,
                    
                    layoutConfig: {
                        animate: true
                    },
                    items: [gridPanel]
                }, {
                    region: 'center',
                    layout: 'fit',
                    border: false,
                    collapsible: true,
                    id: 'img-detail-panel',
                    split: true,
                    width: 670,
                    items: [editform]
                }]
            });//end of viewport


});
